<template>
  <div class="myDialog">
    <!-- 弹窗组件 -->
    <el-dialog :visible.sync="dialogFormVisible" :title="title" :before-close="handleClose" :close-on-click-modal="false" width="450px">
      <el-form
        ref="ruleForm"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item :label="$t('account')" prop="userID">
          <el-input v-model="form.userID" :disabled="form.id ? true: false" :placeholder="`${$t('pleaseInput')}${$t('account')}`"/>
        </el-form-item>
        <el-form-item :label="$t('userName')" prop="userName">
          <el-input v-model="form.userName" :placeholder="`${$t('pleaseInput')}${$t('userName')}`"/>
        </el-form-item>
        <el-form-item :label="$t('department')" prop="department">
          <treeselect
            :options="options"
            v-model="form.department"
            :placeholder="`${$t('pleaseSelect')}${$t('department')}`"
            :no-children-text="$t('noMoreData')"
            :no-options-text="$t('noMoreData')"
            :no-results-text="$t('noMoreData')"
            @input="validDepartment"
          />
        </el-form-item>
        <el-form-item :label="$t('leader')" prop="leader">
          <el-select
            v-model="form.leader"
            :placeholder="`${$t('pleaseInput')}${$t('leader')}`"
            style="width: 100%"
            clearable
            @change="changeLeader"
          >
            <el-option
              v-for="item in leads"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('email')" prop="email">
          <el-input v-model="form.email" :placeholder="`${$t('pleaseInput')}${$t('email')}`"/>
        </el-form-item>
        <el-form-item :label="$t('officePhone')" prop="officePhone">
          <el-input v-model="form.officePhone" :placeholder="`${$t('pleaseInput')}${$t('officePhone')}`"/>
        </el-form-item>
        <el-form-item :label="$t('mobilePhone')" prop="mobilePhone">
          <el-input v-model="form.mobilePhone" :placeholder="`${$t('pleaseInput')}${$t('mobilePhone')}`"/>
        </el-form-item>
        <el-form-item :label="$t('role')" prop="roles">
          <el-select
            v-model="rolesValue"
            :placeholder="`${$t('pleaseInput')}${$t('role')}`"
            style="width: 100%"
            multiple
            @remove-tag="deleteTag"
            @change="changeRole"
          >
            <el-option
              v-for="item in roles"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('description')" prop="description">
          <el-input
            :rows="3"
            v-model="form.description"
            :placeholder="`${$t('pleaseInput')}${$t('description')}`"
            maxlength="200"
            show-word-limit
            type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button icon="el-icon-circle-close" @click="handleClose">{{
          $t("cancel")
        }}</el-button>
        <el-button v-btnThrottle="doSave" type="primary" icon="el-icon-receiving">{{
          $t("save")
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import crudJob from '@/api/system/user'
import { getAllRoles, getUserRoles } from '@/api/system/role'
import { getAllDepts } from '@/api/system/dept'
import mySetting from '@/mixins/mySetting'
import networkTips from '@/mixins/networkTips'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getTreeList } from '@/api/system/dept'
export default {
  name: 'UserModel',
  components: { Treeselect },
  mixins: [mySetting, networkTips],
  data() {
    // 自定义验证
    const validEmail = (rule, value, callback) => {
      const reg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      if (!reg.test(value) && value) {
        callback(new Error(this.$t('incorrectEmailAddress')))
      } else {
        callback()
      }
    }
    const validMoblePhone = (rule, value, callback) => {
      const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
      if (!reg.test(value) && value) {
        callback(new Error(this.$t('numberDoesNotExist')))
      } else {
        callback()
      }
    }
    return {
      rolesValue: [],
      dialogFormVisible: false,
      depts: [], leads: [], roles: [],
      form: {},
      title: '',
      roleDatas: [], // 多选时使用
      userRoles: [],
      options: [],
      rules: {
        userID: [
          { required: true, message: this.$t('userIDRequired'), trigger: 'blur' },
          { min: 2, max: 50, message: this.$t('fieldLengthError'), trigger: 'blur' }
        ],
        userName: [
          { required: true, message: this.$t('userNameRequired'), trigger: 'blur' },
          { min: 2, max: 50, message: this.$t('fieldLengthError'), trigger: 'blur' }
        ],
        department: [
          { required: true, message: this.$t('departmentRequired'), trigger: 'change' }
        ],
        email: [
          { validator: validEmail, trigger: 'blur' }
        ],
        mobilePhone: [
          { validator: validMoblePhone, trigger: 'blur' }
        ]
      } // 表单校验规则
    }
  },
  methods: {
    // 新增数据
    doSave() {
      this.$refs['ruleForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.form.id) {
          // 存在id则是更新
          crudJob.edit({ id: this.form.id, ...this.form, roles: this.rolesValue }).then(res => {
            this.$betterTips(res, this.handleUpdate, this.handleClose)
          })
        } else {
          // 不存在id则是新增
          crudJob.add({ ...this.form, roles: this.rolesValue }).then(res => {
            this.$betterTips(res, this.handleUpdate, this.handleClose)
          })
        }
      })
    },
    // 打开弹窗
    async handleOpen(row) {
      if (row && row.id) {
        this.title = this.$t('modify')
        crudJob.get({ id: row.id }).then(res => {
          this.form = Object.assign({}, res.data, { parentId: res.data.parentId ? res.data.parentId : undefined })
        })
      } else {
        this.title = this.$t('add')
      }
      this.getDepts()
      const data = await getTreeList()
      const formatTree = (root) => {
        return (root || []).map(node => {
          const { id, name, children } = node
          return {
            id,
            label: name,
            children: formatTree(children)
          }
        })
      }
      this.options = formatTree(data.data)
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()
      })
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    // 触发父组件更新
    handleUpdate() {
      this.$emit('initList')
    },
    validDepartment(value) {
      if (value) {
        this.$refs.ruleForm.validateField('department')
      }
    },
    // 获取弹窗内部门数据
    getDepts() {
      getAllDepts().then(res => {
        this.depts = res.data
      }).catch(() => { })

      this.getLeads()
    },
    getLeads() {
      crudJob.getAllUsers().then(res => {
        this.leads = res.data
        this.getRoles()
      }).catch(() => { })
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAllRoles().then(res => {
        this.roles = res.data
        if (this.form.id) {
          getUserRoles({ id: this.form.id }).then(res => {
            this.userRoles = this.userRoles.map(ele => {
              return {
                id: ele
              }
            })
            this.rolesValue = [...res.data]
          })
        }
      })
    },
    changeRole(value) {
      value.forEach((data, index) => {
        this.userRoles.push(data)
      })
    },
    deleteTag(value) {
      this.userRoles.forEach((data, index) => {
        if (data.id === value) {
          this.userRoles.splice(index, value)
        }
      })
    },
    changeDept(value) {
      this.department = value
    },
    changeLeader(value) {
      this.leader = value
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .vue-treeselect__input-container{
  display: flex;
  align-items: center;
}
</style>
